package com.cy.pj.sys.web.interceptor;

import com.cy.pj.common.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalTime;

/**
 * SpringWeb模块定义的拦截器,其接口规范为HandlerInterceptor
 * 当前项目中我们要通过此拦截器对相关资源进行访问时间上的限制
 */
public class TimeAccessInterceptor implements HandlerInterceptor {
    /**
     * 后端handler方法执行之前执行
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 目标处理器对象
     * @return 标识是否对请求进行放行,是否继续执行后续handler方法
     */
    private static final Logger log = LoggerFactory.getLogger(TimeAccessInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //基于JDK中的LocalTime
        LocalTime now = LocalTime.now();
        int hour = now.getHour();
        log.info("hour {}",hour);
        System.out.println(hour);
        if(hour<=6||hour>=24) {
            throw new ServiceException("请求指定时间访问");
        }
        return true;
    }
}
